<template>
  <div class="kh">
    <div class="top flex j-s">
      <div class="left"><span>❤</span> 客户管理</div>
      <div class="right flex">
        <input type="text" v-model="search" placeholder="客户" />
        <el-button class="icon" type="primary" :icon="Search" @click="loadPage"
          >查询</el-button
        >
       
        <el-button
          class="icon"
          color="rgb(103,194,58)"
          type="primary"
          @click="centerDialogVisible = true"
          >+ 新建</el-button
        >
        <el-button class="icon" type="primary" :icon="Edit" @click="edit"
          >编辑</el-button
        >
        <el-button
          class="icon"
          color="rgb(245,108,98)"
          type="primary"
          :icon="Delete"
          @click="open"
          >删除</el-button
        >
        <el-button class="icon op" color="green" type="primary"
          ><span>↑</span> 导入</el-button
        >
        <el-button class="icon op" color="green" type="primary"
          ><span>↓</span>导出</el-button
        >
        <el-button class="gd" color="white" type="primary">*</el-button>
      </div>
    </div>
    <div class="content">
      <el-table
        ref="multipleTableRef"
        :data="tableData"
        :default-sort="{ prop: 'date', order: 'descending' }"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        stripe
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="time" sortable label="创建时间" width="160">
          <!-- <template #default="scope" >{{ scope.row.date }}</template> -->
        </el-table-column>
        <el-table-column prop="name" sortable label="客户姓名" width="160" />
        <el-table-column prop="phone" label="手机" width="160" />
        <el-table-column prop="province" label="省" width="80" />
        <el-table-column prop="city" label="市" width="80" />
        <el-table-column prop="county" label="县" width="80" />
        <el-table-column label="Address" prop="address" show-overflow-tooltip />
      </el-table>
    </div>
    <div class="footer">
      <el-pagination
        v-model:current-page="currentPage4"
        v-model:page-size="pageSize4"
        :page-sizes="[10, 15, 20]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageAll"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 新建的弹窗 -->
    <el-dialog
      v-model="centerDialogVisible"
      title="新建"
      width="40%"
      align-center
    >
      <div class="new">
        <table>
          <tr>
            <td>
              <span>客户：</span><input v-model="getNew.name" type="text" />
            </td>
            <td>
              <span>手机：</span><input v-model="getNew.phone" type="text" />
            </td>
            <td>
              <span>备注：</span><input type="text" v-model="getNew.bz" />
            </td>
          </tr>
          <tr>
            <td>
              <el-cascader  placeholder="请选择省份" @change="change1" v-model="getNew.province" :options="options">
                <template #default="{ node, data }">
                  <span>{{ data.label }}</span>
                  
                </template>
              </el-cascader>
            </td>
            <td>
              <el-cascader placeholder="请选择城市" v-model="getNew.city" @change="change2" :options="options2">
                <template #default="{ node, data }">
                  <span>{{ data.label }}</span>
                  <span v-if="!node.isLeaf">
                    ({{ data.children.length }})
                  </span>
                </template>
              </el-cascader>
            </td>
            <td>
              <el-cascader placeholder="请选择县级" v-model="getNew.county" :options="options3">
                <template #default="{ node, data }">
                  <span>{{ data.label }}</span>
                  <span v-if="!node.isLeaf">
                    ({{ data.children.length }})
                  </span>
                </template>
              </el-cascader>
            </td>
          </tr>
          <tr>
            <td class="inputBig" colspan="3">
              <span>详细地址：</span><input type="text" readonly />
            </td>
          </tr>
        </table>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="gets"> 新建 </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 修改的表格 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑"
      width="40%"
      align-center
    >
      <div class="new">
        <table>
          <tr>
            <td>
              <span>客户：</span><input v-model="editList.name" type="text" />
            </td>
            <td>
              <span>手机：</span><input v-model="editList.phone" type="text" />
            </td>
            <td>
              <span>备注：</span><input type="text" v-model="editList.bz" />
            </td>
          </tr>
           <tr>
            <td>
              <el-cascader placeholder="请选择省份" @change="change1" v-model="editList.province" :options="options">
                <template #default="{ node, data }">
                  <span>{{ data.label }}</span>
                  
                </template>
              </el-cascader>
            </td>
            <td>
              <el-cascader placeholder="请选择城市" v-model="editList.city" @change="change2" :options="options2">
                <template #default="{ node, data }">
                  <span>{{ data.label }}</span>
                  <span v-if="!node.isLeaf">
                    ({{ data.children.length }})
                  </span>
                </template>
              </el-cascader>
            </td>
            <td>
              <el-cascader placeholder="请选择县级" v-model="editList.county" :options="options3">
                <template #default="{ node, data }">
                  <span>{{ data.label }}</span>
                  <span v-if="!node.isLeaf">
                    ({{ data.children.length }})
                  </span>
                </template>
              </el-cascader>
            </td>
          </tr>
          <tr>
            <td class="inputBig" colspan="3">
              <span>详细地址：</span><input type="text" readonly />
            </td>
          </tr>
        </table>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="startEdit"> 确定编辑 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { onBeforeMount } from "vue";
import axios from "axios";
import { ref, reactive, nextTick } from "vue";
import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
} from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
// 

// 定义省级
const options = [
  {
    value: "江苏省",
    label: "江苏省",
  },
  {
    value: "浙江省",
    label: "浙江省",
  },
  {
    value: "安徽省",
    label: "安徽省",
  },
];
// 市级
let options2=reactive([''])
// 省级
let options3=reactive([''])
// 登记市级
const citys=[
  {
    name:'江苏省',
    type:[
      {
      value:'南京市',
      label:'南京市'
      },
      {
      value:'镇江市',
      label:'镇江市'
      },
      {
      value:'徐州市',
      label:'徐州市'
      },
      {
      value:'苏州市',
      label:'苏州市'
      },
      {
      value:'常州市',
      label:'常州市'
      },
    ]
  },
  {
    name:'浙江省',
    type:[
      {
      value:'杭州市',
      label:'杭州市'
      },
      {
      value:'宁波市',
      label:'宁波市'
      },
      {
      value:'温州市',
      label:'温州市'
      },
      {
      value:'嘉兴市',
      label:'嘉兴市'
      },
    ]
  },
  {
    name:'安徽省',
    type:[
      {
      value:'合肥',
      label:'合肥'
      },
      {
      value:'蚌埠市',
      label:'蚌埠市'
      },
      {
      value:'马鞍山市',
      label:'马鞍山市'
      },
      {
      value:'芜湖',
      label:'芜湖'
      },
    ]
  },
]
let countys=[
  {
    name:'南京市',
    type:[
      {
        value:'雨花台区',
        label:'雨花台区',
      },
      {
        value:'秦淮区',
        label:'秦淮区',
      },
      {
        value:'玄武区',
        label:'玄武区',
      },
      {
        value:'江宁区',
        label:'江宁区',
      },
    ]
  },
  {
    name:'镇江市',
    type:[
      {
        value:'丹徒区',
        label:'丹徒区',
      },
      {
        value:'京口区',
        label:'京口区',
      },
      {
        value:'润州区',
        label:'润州区',
      },
    ]
  },
  {
    name:'常州市',
    type:[
      {
        value:'天宁区',
        label:'天宁区',
      },
      {
        value:'新北区',
        label:'新北区',
      },
      {
        value:'武进区',
        label:'武进区',
      },
    ]
  },
  {
    name:'苏州市',
    type:[
      {
        value:'太仓区',
        label:'太仓区',
      },
      {
        value:'姑苏区',
        label:'姑苏区',
      },
      {
        value:'吴江区',
        label:'吴江区',
      },
    ]
  },
  {
    name:'徐州市',
    type:[
      {
        value:'鼓楼区',
        label:'鼓楼区',
      },
      {
        value:'贾汪区',
        label:'贾汪区',
      },
      {
        value:'泉山区',
        label:'泉山区',
      },
    ]
  },
  {
    name:'杭州市',
    type:[
      {
        value:'上城区',
        label:'上城区',
      },
      {
        value:'下城区',
        label:'下城区',
      },
      {
        value:'钱塘区',
        label:'钱塘区',
      },
    ]
  },
  {
    name:'宁波市',
    type:[
      {
        value:'海曙区',
        label:'海曙区 ',
      },
      {
        value:'北仑区',
        label:'北仑区',
      },
      {
        value:'鄞州区',
        label:'鄞州区',
      },
    ]
  },
  {
    name:'温州市',
    type:[
      {
        value:'鹿城区',
        label:'鹿城区 ',
      },
      {
        value:'龙湾区',
        label:'龙湾区',
      },
    ]
  },
  {
    name:'嘉兴市',
    type:[
      {
        value:'南湖区',
        label:'南湖区 ',
      },
      {
        value:'秀洲区',
        label:'秀洲区',
      },
    ]
  },
  {
    name:'合肥',
    type:[
      {
        value:'瑶海区',
        label:'瑶海区 ',
      },
      {
        value:'庐阳区',
        label:'庐阳区',
      },
    ]
  },
  {
    name:'蚌埠',
    type:[
      {
        value:'龙子湖区',
        label:'龙子湖区 ',
      },
      {
        value:'蚌山区',
        label:'蚌山区',
      },
    ]
  },
  {
    name:'马鞍山',
    type:[
      {
        value:'花山区',
        label:'花山区 ',
      },
      {
        value:'博望区',
        label:'博望区',
      },
    ]
  },
  {
    name:'芜湖',
    type:[
      {
        value:'镜湖区',
        label:'镜湖区 ',
      },
      {
        value:'鸠江区',
        label:'鸠江区',
      },
    ]
  },
]
// 判断省级后的市级
let change1=(e)=>{
  // console.log(e[0]);
  citys.forEach(r=>{
    if(r.name==e[0]){
      options2=r.type
    }
  })
  getNew.county=''
}
// 判断市级后的省级
let change2=(e)=>{
  console.log(e);
  countys.forEach(r=>{
    if(r.name==e[0]){
      options3=r.type
    }
  })
}

// 定义新建弹窗开启状态
let centerDialogVisible = ref(false);
// 定义编辑弹窗开启的状态
let editDialogVisible = ref(false);
// 分页
const currentPage4 = ref(1);
const pageSize4 = ref(10);
const background = ref(false);
const disabled = ref(false);
const small = ref(false);
// 定义查询
const search = ref("");

let pageAll = ref("");
const multipleTableRef = ref();

const toggleSelection = (rows) => {
  if (rows) {
    rows.forEach((row) => {
      // TODO: improvement typing when refactor table
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-expect-error
      multipleTableRef.value.toggleRowSelection(row, undefined);
    });
  } else {
    multipleTableRef.value.clearSelection();
  }
};

// 分页
const handleSizeChange = (val) => {
  loadPage();
  console.log(`${val} items per page`);
};
const handleCurrentChange = (val) => {
  loadPage();
  console.log(`current page: ${val}`);
};

// 数组数据
let tableData = ref([]);
onBeforeMount(() => {
  loadPage();
});
// 加载内容数据
const loadList = async () => {
  let { data } = await axios.get("sg");
  tableData.value = data;
  // console.log(tableData.value.length);
};
// 加载分页数据
const loadPage = async () => {
  console.log("aaa");
  let { data } = await axios.get("sg/Page", {
    params: {
      currentPage4: currentPage4.value,
      pageSize4: pageSize4.value,
      search: search.value,
    },
  });
  tableData.value = data.data;
  pageAll.value = data.count;
};

// 清空新建内容数据
let clearNew = () => {
  getNew = reactive({
    id: "",
    time: "",
    name: "",
    phone: "",
    province: "",
    city: "",
    county: "",
    master: "",
    address: "",
    bz: " ",
  });
};
// 格式化日对象
const getNowDate = () => {
  var date = new Date();
  var sign2 = ":";
  var year = date.getFullYear(); // 年
  var month = date.getMonth() + 1; // 月
  var day = date.getDate(); // 日
  var hour = date.getHours(); // 时
  var minutes = date.getMinutes(); // 分
  var seconds = date.getSeconds(); //秒
  var weekArr = [
    "星期一",
    "星期二",
    "星期三",
    "星期四",
    "星期五",
    "星期六",
    "星期天",
  ];
  var week = weekArr[date.getDay()];
  // 给一位数的数据前面加 “0”
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (day >= 0 && day <= 9) {
    day = "0" + day;
  }
  if (hour >= 0 && hour <= 9) {
    hour = "0" + hour;
  }
  if (minutes >= 0 && minutes <= 9) {
    minutes = "0" + minutes;
  }
  if (seconds >= 0 && seconds <= 9) {
    seconds = "0" + seconds;
  }
  return (
    year +
    "-" +
    month +
    "-" +
    day +
    " " +
    hour +
    sign2 +
    minutes +
    sign2 +
    seconds
  );
};

// 定义新建数据
let getNew = reactive({
  id: "",
  time: "",
  name: "",
  phone: "",
  province: "",
  city: "",
  county: "",
  master: "",
  address: "",
  bz: "",
});
// 进行新建
let gets = async () => {
  centerDialogVisible.value = false;
  let { data } = await axios.post("sg/push", {
    id: tableData.value.length + 1,
    time: getNowDate(),
    name: getNew.name,
    phone: getNew.phone,
    province: getNew.province,
    city: getNew.city,
    county: getNew.county,
    master: getNew.master,
    address: getNew.province + getNew.city + getNew.county,
  });
  console.log(tableData);
  loadPage();
  clearNew();
};
// 进行编辑操作
// 定义获取被点击的数据
const multipleSelection = ref([]);
let editList = ref({});
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
  // console.log(multipleSelection);
};
// 数据内部清空
let clear = () => {
  editList= ref({
    id: "",
    time: "",
    name: "",
    phone: "",
    province: "",
    city: "",
    county: "",
    master: "",
    address: "",
    bz: "",
  });
};

// 只能一行进行编辑的判断
let edit = async () => {
  if (multipleSelection.value.length == 1) {
    editDialogVisible.value = true;
    let { data } = await axios.get("sg/find", {
      params: {
        id: multipleSelection.value[0].id,
      },
    });
    editList.value = data;
    console.log(editList);
    // editList=data
    //  console.log('可以编辑',editList);
  } else {
    alert("一次只可对一行数据进行编辑");
  }
};
// 确定编辑
let startEdit = async () => {
  // console.log(editList.value);
  let { data } = await axios.post("sg/change", {
    id: editList.value.id,
    time: getNowDate(),
    name: editList.value.name,
    phone: editList.value.phone,
    province: editList.value.province,
    city: editList.value.city,
    county: editList.value.county,
    master: editList.value.master,
    address: editList.value.address,
    bz: editList.value.bz,
  });
  // console.log(editList);
  loadPage();
  editDialogVisible.value = false;
};

// 定义删除弹窗
const open = () => {
  if (multipleSelection.value.length > 0) {
    ElMessageBox.confirm("你确定要删除嘛", {
      confirmButtonText: "确定删除",
      cancelButtonText: "取消删除",
      type: "warning",
      center: true,
    })
      .then(async () => {
        ElMessage({
          type: "success",
          message: "删除成功",
        });
        let { data } = await axios.post("sg/delete", {
          id: multipleSelection.value,
        });
        loadPage();
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "Delete canceled",
        });
      });
  } else {
    alert("请选择数据进行删除");
  }
};
</script>
<style scoped lang='scss'>
* {
  margin: 0;
  padding: 0;
  list-style: none;
  text-decoration: none;
  box-sizing: border-box;
}
.flex {
  display: flex;
}
.j-s {
  justify-content: space-between;
}
.a-c {
  align-items: center;
}
.j-c {
  justify-content: center;
}
.top {
  height: 50px;
  line-height: 50px;
  padding: 0 30px;
}
.left {
  border-bottom: 3px solid black;
  span {
    font-size: 20px;
    font-weight: bold;
    color: pink;
  }
}
.right {
  //   width: 900px;
  input {
    width: 150px;
    height: 30px;
    padding-left: 15px;
    margin-right: 15px;
    border-radius: 5px;
    border: 2px solid rgb(204, 191, 191);
    opacity: 0.7;
  }
  .icon {
    width: 90px;
    height: 35px;
    color: white;
    span {
      font-size: 20px;
      font-weight: bold;
      margin-right: 5px;
    }
  }
  .op {
    opacity: 0.5;
  }
  .gd {
    width: 30px;
    padding: 0 10px;
    height: 35px;
    // line-height: 35px;
    font-weight: bold;
    font-size: 25px;
    border: 1px solid #333;
  }
}
.content {
  margin-top: 10px;
  padding: 0 30px;
  // border: 1px solid #eee;
}
.footer {
  margin-top: 10px;
  position: absolute;
  right: 10px;
  padding: 0 30px;
}
.new {
  table {
    width: 100%;
    tr {
      td {
        padding: 5px 10px;
        width: 200px;
        text-align: right;
       
        input {
          margin-left: 8px;
          width: 155px;
        }
      }
      .inputBig {
        padding-top: 20px;
        input:last-child {
          width: 85%;
          height: 50px;
        }
      }
    }
  }
}

.kh {
  height: 80vh;
  // border: 1px solid red;
  position: relative;
  .footer {
    // width: 100vw;
    width: 100%;
    height: 50px;
    line-height: 50px;
   
    padding-left: 60%;
  }
}
</style>